/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package maincz.tests.webapp.backingbeans;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlDataTable;
import maincz.tests.webapp.entity.contactbook.Contact;
import maincz.tests.webapp.service.IContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author Main
 */
@Component("contactsBean")
@SessionScoped
public class ContactsBean implements Serializable {
        
    @Autowired
    private IContactService contactService;

    private Contact newContact;
    
    private HtmlDataTable dataTable; 
    
    private static final Logger log = Logger.getLogger("MyLogger");

    public ContactsBean() {
        super();
        this.newContact = new Contact();
    }

    public Integer getContactsCount() {
        return this.contactService.listContacts().size();
    }
    
    public List<Contact> getContacts() {
        return this.contactService.listContacts();
    }

    public Contact getNewContact() {
        return newContact;
    }

    public void setNewContact(Contact newContact) {
        this.newContact = newContact;
    }

    public IContactService getContactService() {
        return contactService;
    }

    public void setContactService(IContactService contactService) {
        this.contactService = contactService;
    }

    public HtmlDataTable getDataTable() {
        return dataTable;
    }

    public void setDataTable(HtmlDataTable dataTable) {
        this.dataTable = dataTable;
    }
        
    
    public void storeContact() {
        log.info("Adding contact " + this.newContact.toString());
        this.contactService.addContact(newContact);
        this.newContact = new Contact();        
    }
    
    public void removeContact() {
        //ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        //Long id = Long.parseLong((String)externalContext.getRequestParameterMap().get("contactId"));  
        Contact c = (Contact) getDataTable().getRowData();        
        if (c != null) {
            log.info("Remove contact, id " + c.getId());
            this.contactService.removeContact(c.getId());
        }
    }
    
}
